# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: api\filters\sqlalchemy_adapter.py
from sqlalchemy import and_ as sqlalchemy_and
from sqlalchemy import or_ as sqlalchemy_or
import sqlalchemy.sql.operators as sql_operators


def get_sqlachemy_filter(expressions, column, filter_descriptor):
    """
    Transforms a simple key:(operator)values (already preprocessed) expression to sql alchemy filter
    :param expressions:
    :param column:
    :param filter_descriptor:
    :return:
    """
    filter_expression = []
    for and_expression in expressions:
        operator, operands = and_expression
        if filter_descriptor.get("multiple_values", False):
            or_filters = []
            for operand in operands:
                or_filters.append(getattr(sql_operators, operator)(column, operand))

            c = len(or_filters)
            if c == 1:
                filter_expression.append(or_filters[0])
            elif c > 1:
                filter_expression.append(sqlalchemy_or(*or_filters))
            else:
                if operands:
                    operand = operands[0]
                    if operator == "ilike_op":
                        operand = "%" + operand + "%"
                    filter_expression.append(
                        getattr(sql_operators, operator)(column, operand)
                    )

    count = len(filter_expression)
    if count > 1:
        return sqlalchemy_and(*filter_expression)
    if filter_expression:
        return filter_expression[0]
